package com.gxh.text.utiles;

import com.gxh.text.entity.Users;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;

/**
 * 保存和获取当前用户的工具类
 */
public class UserContext {
    private static  final  String CURRENT_USER_IN_SESSION = "login";
    /**
     * 得到session
     */
    private  static HttpSession getSession(){
        //SpringMVC获取session的方式通过RequestContextHolder
        return  ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
    }
    /**
     * 设置当前用户到session中
     */
    public  static  void putCurrebtUser(Users users){
        getSession().setAttribute(CURRENT_USER_IN_SESSION,users);
    }
    /**
     * 获取当前用户
     */
    public  static  Users getCurreentUser(){
        return (Users) getSession().getAttribute(CURRENT_USER_IN_SESSION);
    }
}
